package com.shwread.android.qysw.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.widget.TextSearchPopup;

import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.util.UIUtil;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.text.model.ZLTextPlainModel;

import java.util.ArrayList;

import logic.bean.SearchResultInfo;
import logic.util.Util;


public class SearchActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener,
        OnItemClickListener
{
	private static boolean      bool = true;
	public FBReaderApp          myFBReaderApp;
	/** VIEW */
	private EditText            evSearchPattern;
	private Button              btnSearchStart;
	private TextView            tvSearchResult;
	private ListView            lvSearchResult;
	private SearchResultAdapter searchResultAdapter;
	Handler handler = new Handler()
	                {
		                public void handleMessage(android.os.Message msg) {
			                switch (msg.what) {
								case 1:
									searchResultAdapter = new SearchResultAdapter();
									searchResultAdapter.searchResultInfos = ((ZLTextPlainModel) myFBReaderApp.getTextView().getModel()).getSearchResultInfos();
									lvSearchResult.setAdapter(searchResultAdapter);
									tvSearchResult.setVisibility(View.VISIBLE);
									tvSearchResult.setText("已经找到" + searchResultAdapter.searchResultInfos.size() + "个结果");
								    Util.hideInputMethodManager(SearchActivity.this, evSearchPattern);
									break;
								
								default:
									break;
							}
						};
	                };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result);
		initView();
		addListener();
		myFBReaderApp = (FBReaderApp) FBReaderApp.Instance();
		if (myFBReaderApp == null)
		{
			myFBReaderApp = new FBReaderApp(new BookCollectionShadow());
		}
	}
	
	private void initView() {
		evSearchPattern = (EditText) findViewById(R.id.search_pattern_et);
		btnSearchStart = (Button) findViewById(R.id.search_start_btn);
		tvSearchResult = (TextView) findViewById(R.id.search_result_tv);
		lvSearchResult = (ListView) findViewById(R.id.search_result_lv);
		ImageView back = (ImageView) findViewById(R.id.read_search_page_turning_btn);
		back.setOnClickListener(this);
	}
	
	private void addListener() {
		btnSearchStart.setOnClickListener(this);
		evSearchPattern.setOnEditorActionListener(new OnEditorActionListener()
		{
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				switch (actionId) {
				
					case EditorInfo.IME_ACTION_SEARCH:
						startSearch(evSearchPattern.getText().toString());
						break;
				
				}
				return false;
			}
		});
		lvSearchResult.setOnItemClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.search_start_btn:
				startSearch(evSearchPattern.getText().toString());
				break;
			case R.id.read_search_page_turning_btn:
				onBackPressed();
				break;
			default:
				break;
		}
	}
	
	private void startSearch(final String text) {
		if (Util.isNotEmpty(text))
		{
			final Runnable runnable = new Runnable()
			{
				public void run() {
					final TextSearchPopup popup = (TextSearchPopup) myFBReaderApp.getPopupById(TextSearchPopup.ID);
					popup.initPosition();
					myFBReaderApp.TextSearchPatternOption.setValue(text);
					if (myFBReaderApp.getTextView().search(text, true, false, false, false) != 0)
					{
						handler.sendEmptyMessage(1);
					}
					else
					{
						runOnUiThread(new Runnable()
						{
							public void run() {
								Util.showToast(SearchActivity.this, "抱歉，未搜索到结果！");
								popup.StartPosition = null;
							}
						});
					}
				}
			};
			UIUtil.wait("search", runnable, this);
		} else {
			Util.showToast(this, "搜索内容不能为空！");
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		SearchResultInfo searchResultInfo = searchResultAdapter.searchResultInfos.get(position);
		myFBReaderApp.BookTextView.gotoPosition(searchResultInfo.getFixedPosition());
		myFBReaderApp.getViewWidget().repaint();
		finish();
	}
	
	class SearchResultAdapter
	        extends
	        BaseAdapter
	{
		
		ArrayList<SearchResultInfo> searchResultInfos = new ArrayList<SearchResultInfo>();
		
		@Override
		public int getCount() {
			return searchResultInfos.size();
		}
		
		@Override
		public Object getItem(int position) {
			return searchResultInfos.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return 0;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
			{
				convertView = LayoutInflater.from(SearchActivity.this).inflate(R.layout.search_result_item, null);
			}
			TextView tvContent = (TextView) convertView.findViewById(R.id.search_result_item_content);
			TextView tvProcess = (TextView) convertView.findViewById(R.id.search_result_item_process);
			
			SearchResultInfo resultInfo = searchResultInfos.get(position);
			String textStr = resultInfo.getText();
			SpannableStringBuilder style = new SpannableStringBuilder(textStr);
			String  searchStr = evSearchPattern.getText().toString();
			int start = textStr.indexOf(searchStr);
			style.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.common_press_font_bg)), start, start + searchStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			tvContent.setText(style);
			
			return convertView;
		}
		
	}
}
